#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    table = new PTableWidget( this );

    taskEd = new taskEditor( this );

    paramDlg = new paramChooseDialog( this );

    viewInputDlg = new ViewInputDialog( this );

    resultPrintDlg = new ResultPaintDialog ( this );

    //assist = 0;
    helpDlg = 0;

    //taskEd->show();
    //table->setRowCount(15);
    //table->setColumnCount(4);
    table->setSelectionBehavior( QAbstractItemView::SelectRows );
    table->setEditTriggers( QAbstractItemView::NoEditTriggers );
    setCentralWidget( table );

    createActions();
    createMenus();
    createToolBars();

    loadData();

    setWindowTitle(tr("Program for solving openshop tasks"));

    //connect( table, SIGNAL(cellDoubleClicked(int,int)), this, SLOT(editTask(int,int)) );
    connect( paramDlg, SIGNAL(itemMade(taskType)), this, SLOT(taskMade(taskType)) );
}

void MainWindow::createActions()
{
    newAction = new QAction(tr("&New"), this);
    newAction->setIcon(QIcon("icons/add.png"));

    editAction = new QAction( tr("&Edit"), this );
    editAction->setIcon(QIcon("icons/edit.png"));

    deleteAction = new QAction(tr("&Delete"), this);
    deleteAction->setIcon(QIcon("icons/delete.png"));

    viewResultAction = new QAction(tr("&View Results"), this);
    viewResultAction->setIcon( QIcon("icons/view result.png") );

    viewInputAction = new QAction(tr("&View Input"), this);
    viewInputAction->setIcon( QIcon("icons/view input.png") );

    helpAction = new QAction(tr("&Help"), this);
    helpAction->setIcon( QIcon("icons/help.png") );


    connect( newAction, SIGNAL(triggered()), this, SLOT(newTask()) );
    connect( editAction, SIGNAL(triggered()), this, SLOT(editTask()) );
    connect( deleteAction, SIGNAL(triggered()), this, SLOT(deleteTask()) );
    connect( viewInputAction, SIGNAL(triggered()), this, SLOT(viewTaskInput()) );
    connect( viewResultAction, SIGNAL(triggered()), this, SLOT(viewTaskResult()) );

    connect( helpAction, SIGNAL(triggered()), this, SLOT(showHelp()) );
}

void MainWindow::createMenus()
{
    fileMenu = menuBar()->addMenu(tr("&File"));
    fileMenu->addAction( newAction );
    fileMenu->addAction( editAction );
    fileMenu->addAction( deleteAction );
    fileMenu->addSeparator();
    fileMenu->addAction( viewInputAction );
    fileMenu->addAction( viewResultAction );
}

void MainWindow::createToolBars()
{
    fileToolBar = addToolBar(tr("&File"));
    fileToolBar->addAction( newAction );
    fileToolBar->addAction( editAction );
    fileToolBar->addAction( deleteAction );
    fileToolBar->addSeparator();
    fileToolBar->addAction( viewInputAction );
    fileToolBar->addAction( viewResultAction );
    fileToolBar->addSeparator();
    fileToolBar->addAction( helpAction );
}

void MainWindow::editTask()
{
    QVector<itemType> items;
    table->getItems( items );

    int row = selectedRow();
    if (row == -1) return;

    taskType task;
    task.setByItemType( items[row] );

    lastReason = 1;
    rowClicked = row;

    paramDlg->setReason( lastReason, task );
    paramDlg->exec();
}

void MainWindow::newTask()
{
    //taskEd->exec();
    lastReason = 0;
    paramDlg->setReason( lastReason, taskType() );
    paramDlg->exec();
}

void MainWindow::deleteTask()
{
    int row = selectedRow();
    if (row == -1) return;
    table->deleteItem( row );
}

void MainWindow::viewTaskInput()
{
    QVector<itemType> items;
    table->getItems( items );

    taskType task;
    int row = selectedRow();
    if (row == -1) return;
    task.setByItemType( items[row] );
    task.loadInputFromFile( inputPrefix + task.getName() );

    viewInputDlg->setInputTable( task.input );
    viewInputDlg->exec();
}

void MainWindow::viewTaskResult()
{
    QVector<itemType> items;
    table->getItems( items );

    taskType task;
    int row = selectedRow();
    if (row == -1) return;
    task.setByItemType( items[row] );
    task.loadInputFromFile( inputPrefix + task.getName() );
    task.loadOutputFromFile( outputPrefix + task.getName() );

    resultPrintDlg->setTaskParams( task.input, task.output );
    resultPrintDlg->exec();

}

int MainWindow::selectedRow()
{
    if (table->currentRow() == -1){
        QMessageBox::warning( this, tr("warning"), tr("No task is selected") );
        return - 1;
    } else return table->currentRow();
}

void MainWindow::showHelp()
{
    if (helpDlg == 0){
        helpDlg = new helper(this);
    }
    //assist->showDocumentation("introduction.html");
    helpDlg->exec();
}

void MainWindow::taskMade( taskType task )
{
    this->task = task;
    if (lastReason == 0)
        table->insertItem( task ); else
            table->editItem( rowClicked, task );

    //int res = slv( task.input.size(), task.input[0].size(), task.input );
    //solve( task );

    //for resizing
    this->task.output = this->task.input;

    QStringList algos ( QStringList() << QObject::tr("Full Bust") << QObject::tr("Full Bust with amputation") );

    //int opt;
    QString optName = this->task.getOptimization();
    if (optName == tr("Last end"))
        opt = 0; else
            opt = 1;
    //int opt = optim.indexOf(this->task.getOptimization());
    QString algName = this->task.getAlgorithm();
    int alg = algo.indexOf(this->task.getAlgorithm());
    if (algName == tr("Full Bust"))
        alg = 0; else
            alg = 1;

    if (alg == 0)
        FullBust( this->task.input, this->task.output, opt );
            else
                FullBustWithAmputations( this->task.input, this->task.output, opt );

    saveTaskInputOutput();
    saveData();


    /*QFile output("output.txt");
    output.open( QFile::WriteOnly );

    QTextStream out(&output);

    out  << res;

    output.close();*/
}

void MainWindow::saveTaskInputOutput()
{
    QFile inputFile(inputPrefix + task.getName());
    QFile outputFile( outputPrefix + task.getName() );

    inputFile.open( QFile::WriteOnly );
    outputFile.open( QFile::WriteOnly );

    QTextStream out;
    out.setDevice( &inputFile );

    out << task.input.size() << " " << task.input[0].size() << "\n";
    for (int i=0; i<task.input.size(); i++){
        for (int j=0; j<task.input[0].size(); j++)
            out << task.input[i][j] << " ";
        out << "\n";
    }

    inputFile.close();

    out.setDevice( &outputFile );

    out << task.output.size() << " " << task.output[0].size() << "\n";
    for (int i=0; i<task.output.size(); i++){
        for (int j=0; j<task.output[0].size(); j++)
            out << task.output[i][j] << " ";
        out << "\n";
    }

    outputFile.close();
}

void MainWindow::saveData()
{
    table->saveData();

    /*taskType task;
    QVector<itemType> items;
    //QVector<taskType> tasks;
    table->getItems( items );

    for (int i=0; i<items.size(); i++){
        task.setByItemType( items[i] );
        //tasks.push_back( task );
        QFile file( inputPrefix );
        file.open( QFile::WriteOnly );

        QDataStream out( file );

        for (int i=0; i<)

        file.close();
    }

    //for ()*/
}

void MainWindow::loadData()
{
    table->loadData();
}

/*void MainWindow::run( int mach, int num )
{
    int maxsum = -1;
    int sum;
    if (num == n){
        //check for optimal
        for (int i=0; i<m; i++)
        {
            sum = 0;
            for (int j=0; j<n; j++)
                sum += task.input[ order[j][i] ][i];
            if (sum > maxsum) maxsum = sum;
        }
        if (sum < minimal) minimal = sum;
        return;
    }

    for (int i=0; i<n; i++)
        if (!colHas[mach][i] && !rowHas[num][i]){
            order[num][mach] = i;
            colHas[mach][i] = true;
            rowHas[num][i] = true;

            if (mach == m-1) run(0, num+1); else run(mach+1, num);
            colHas[mach][i] = false;
            rowHas[num][i] = false;
        }

    // n < m
    order[num][mach] = -1;
    if (mach == m-1) run(0, num+1); else run(mach+1, num);
}*/

/*void MainWindow::solve( taskType task )
{
    n = task.input.size();
    m = task.input[0].size();
    minimal = 10000;

    order.resize( n );
    for(int i=0; i<n; i++)
        order[i].resize( m );

    rowHas.resize( n );
    for (int i=0; i<n; i++)
        rowHas[i].resize( n );

    for (int i=0; i<n; i++)
        for (int j=0; j<n; j++)
            rowHas[i][j] = false;

    colHas.resize( m );
    for (int i=0; i<m; i++)
        colHas[i].resize( n );

    for (int i=0; i<m; i++)
        for (int j=0; j<n; j++)
            colHas[i][j] = false;

    run(0, 0);

    QFile output("output.txt");
    output.open( QFile::WriteOnly );

    QTextStream out(&output);

    out  << minimal;

    output.close();
}*/

/*void MainWindow::saveTasksList( bool def )
{
    QFile data("tasks.dat");
    data.open(QIODevice::WriteOnly);
    QDataStream out(&data);

    if ( def ) {
        out << 0; //number of tasks
    } else {
        out << tasksCount;
        for (int i=0; i<tasksCount; i++)
            out << tasks[i];
    }

    data.close();
}

void MainWindow::saveHeadersList( bool def )
{
    QFile data("header.dat");
    data.open(QIODevice::WriteOnly);
    QDataStream out(&data);

    if ( def ) {
        out << visibleFields; //number of fields
        out << "Name" << "Description" << "Algorithm" <<
                "Last execution";
    } else {
        out << visibleFields;
        for (int i=0; i<visibleFields; i++)
            out << headers[i];
    }

    data.close();

}

void MainWindow::loadTasksList()
{
    QFile data("tasks.dat");
    data.open(QIODevice::ReadOnly);
    QDataStream in(&data);

    in >> tasksCount;
    tasks.resize( tasksCount );
    for (int i=0; i<tasksCount; i++)
        in >> tasks[i];

    data.close();
}

void MainWindow::loadHeaderList()
{
    QFile data("header.dat");
    data.open(QIODevice::ReadOnly);
    QDataStream in(&data);

    int temp;
    in >> temp;
    headers.resize( temp );
    for (int i=0; i<temp; i++)
        in >> headers[i];

    data.close();


}
*/
MainWindow::~MainWindow()
{

}
